package com.atguigu.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * com.atguigu.hbase
 *
 * @author jing.liang
 * 日期2022-05-09 22:53
 */
public class HbaseDemo {

    public static void main(String[] args) throws IOException {
        createTable(null, "emp", "info1", "info2");
    }

    /**
     * DML - 插入数据/修改数据
     * @param namespace
     * @param tableName
     * @param rk
     * @param cf
     * @param cl
     * @param value
     */
    public static void putData(String namespace, String tableName, String rk, String cf, String cl, String value) throws IOException {
        // 获取Table对象
        TableName tn = TableName.valueOf(namespace, tableName);
        Table table = connection.getTable(tn);
        Put put = new Put(Bytes.toBytes(rk));
        put.addColumn(Bytes.toBytes(cf), Bytes.toBytes(cl), Bytes.toBytes(value));
        table.put(put);

        table.close();
    }

    /**
     * DDL - 创建表
     * create 'ns:tn', 'cf' ...
     * @param namespace
     * @param tableName
     * @param cfs
     * @throws IOException
     */
    public static void createTable(String namespace, String tableName, String... cfs) throws IOException {
        Admin admin = connection.getAdmin();
        // 先判断表是否已经存在
        TableName tn = TableName.valueOf(namespace, tableName);
        boolean exists = admin.tableExists(tn);
        if (exists) {
            System.out.println((namespace == null ? "default" : namespace) + ":" + tableName + " 表已经存在");
            return;
        }

        // 创建表
        TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tn);
        // 设置列族
        for (String cf : cfs) {
            ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(cf));
            ColumnFamilyDescriptor columnFamilyDescriptor = columnFamilyDescriptorBuilder.build();
            tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptor);
        }

        TableDescriptor tableDescriptor = tableDescriptorBuilder.build();

        admin.createTable(tableDescriptor);
        System.out.println((namespace == null ? "default" : namespace) + ":" + tableName + " 表创建成功");
        admin.close();
    }

    /**
     * 创建connection对象
     */
    private static Connection connection;

    static {
//        Configuration configuration = new Configuration();
        Configuration configuration = HBaseConfiguration.create();
        // 指定hbase的地址
        configuration.set("hbase.zookeeper.quorum", "project105,project106,project107");
        try {
            connection = ConnectionFactory.createConnection(configuration);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
